package com.sny.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * @Author: yzm
 * @Description: 线程池配置
 * @Date: 2020/08/14 19:58
 * @Modified:
 **/
@Configuration
@Slf4j
public class ThreadPoolExecutorConfig {
    /*
    * 核心线程线程数
    * */
    @Value("${thread-pool.core-pool-size}")
    private Integer corePoolSize;
    /*
     * 最大线程数，非核心线程 = 最大线程数 - 核心线程线程数
     * */
    @Value("${thread-pool.max-pool-size}")
    private Integer maxPoolSize;
    /*
     * 非核心线程最大存活时间
     * */
    @Value("${thread-pool.keep-alive-seconds}")
    private Integer keepAliveSeconds;
    /*
     * 队列深度
     * */
    @Value("${thread-pool.queue-capacity}")
    private Integer queueCapacity;

    final ThreadFactory threadFactory = new ThreadFactoryBuilder()
            // -%d不要少
            .setNameFormat("async-task-name-%d")
            .setDaemon(true)
            .build();

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveSeconds, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueCapacity),
                threadFactory, (r, executor) -> {
            // 打印日志,添加监控等
            log.error("task is rejected!");
        });
    }
}
